/**
 * Created by neal on 11/22/16.
 */

$(".datepicker").datepicker({
    todayBtn: "linked",
    clearBtn: true,
    autoclose: true,
    language: "zh-CN"
});

var Config = {
    updateUrl: '/api/admin/company',
    selectLogisticsNameUrl: '/api/admin/logistics/name',
    updateAuditUrl: '/api/admin/company/audit',

    selectUrl: '/api/admin/company/exPrice',
    updateExUrl: '/api/admin/company/exPrice',
    updateUrlForCellEdit: '/api/admin/company/exPrice/cellEdit',

    selectDistrictsUrl: '/api/districts/page',
    selectIndustryUrl:'/api/admin/industry/selectAll',
    selectTypeUrl:'/api/admin/type/selectAll',
    selectIndustryByPkUrl:'/api/admin/industry/selectByPk/',
    selectTypeByPkUrl:'/api/admin/type/selectByPk/',
    selectDistrictsOneUrl: '/api/districts'
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});
// $("#province").click(function () {
//     getDistrictByParentId(0, "#province");
// });
$("#province").change(function(){
    var id = $(this).val();
    var html = [];
    var selectId = '#city';
    if(id == 1){
        html.push('<option value="'+1+'">'+'北京市'+'</option>');
        $(selectId).html(html.join(''));
        getDistrictByParentId(id, "#district");
    } else if(id == 2){
        html.push('<option value="'+2+'">'+'天津市'+'</option>');
        $(selectId).html(html.join(''));
        getDistrictByParentId(id, "#district");
    } else if(id == 3){
        html.push('<option value="'+3+'">'+'上海市'+'</option>');
        $(selectId).html(html.join(''));
        getDistrictByParentId(id, "#district");
    } else if(id == 4){
        html.push('<option value="'+4+'">'+'重庆市'+'</option>');
        $(selectId).html(html.join(''));
        getDistrictByParentId(id, "#district");
    } else {
        $("#district").html("");
        $.ajax({
            url: Config.selectDistrictsUrl,
            data: {parentid:id , page: 1, rows: 1000,name: name},
            type: "GET",
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                getDistrictByParentId(id, "#city");
                $("input[name=districtId]").val(id);

            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error("网络故障");
            }
        });
    }
});
$("#city").change(function(){
    var id = $(this).val();
    $.ajax({
        url: Config.selectDistrictsUrl,
        data: {parentid:id , page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            getDistrictByParentId(id, "#district");
            $("input[name=districtId]").val(id);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
});
$("#district").change(function(){
    $("input[name=districtId]").val($(this).val());
});
function getDistrictByParentId(id, selectId) {
    $.ajax({
        url: Config.selectDistrictsUrl,
        data: {parentid:id, page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        async: false,
        success: function (data, textStatus, jqXHR) {
            var html = [];
            html.push('<option value="'+0+'">'+'请选择地区'+'</option>');
            data.data.forEach(function(item){
                html.push('<option value="'+item.id+'">'+item.name+'</option>');
            });
            $(selectId).html(html.join(''));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
}
function getDistrictById(id, selectId) {
    $.ajax({
        url: "/api/admin/districts",
        data: {id:id},
        type: "GET",
        dataType: "json",
        async: false,
        success: function (data, textStatus, jqXHR) {
            var html = [];
            html.push('<option value="'+data.data.id+'">'+data.data.name+'</option>');
            $(selectId).html(html.join(''));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
}



$().ready(function () {

    $.ajax({
        url: Config.selectDistrictsOneUrl,
        data: {name:$("input[id=pr]").val()},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            $("input[id=pr]").val(data.data[0].id);
            $("#province").val($("input[id=pr]").val());
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("地址获取错误！");
        }
    });

    $.ajax({
        url: Config.selectDistrictsOneUrl,
        data: {name:$("input[id=ct]").val()},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            $("input[id=ct]").val(data.data[0].id);
            getDistrictById($("input[id=ct]").val(),"#city");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("地址获取错误！");
        }
    });

    $.ajax({
        url: Config.selectDistrictsOneUrl,
        data: {name:$("input[id=dr]").val()},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            $("input[id=dr]").val(data.data[0].id);
            getDistrictById($("input[id=dr]").val(),"#district");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("地址获取错误！");
        }
    });

    getDistrictByParentId(0, "#province");

    var pr=Number($("input[id=pr]").val());
    var ct=Number($("input[id=ct]").val());
    var dr=Number($("input[id=dr]").val());

    // if (pr != 0 && pr != NaN){
    //     $("#province").val($("input[id=pr]").val());
    // }
    // if (ct != 0 && ct != NaN) {
    //     getDistrictById($("input[id=ct]").val(),"#city");
    // }
    // if (dr != 0 && dr != NaN) {
    //     getDistrictById($("input[id=dr]").val(),"#district");
    // }
    var  companyTypeId=$("input[id=companyTypeId]").val();
    console.log(companyTypeId);
    var  industryId;



    $.ajax(
        {
            url: Config.selectTypeUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="" hassubinfo="true">请选择</option>');
                data.data.map(function (type) {
                    categories.push('<option value="');
                    categories.push(type.id);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(type.name);
                    categories.push('</option>');
                    if (companyTypeId == type.id){
                        industryId=type.industryId;
                        console.log(industryId);
                    }
                });
                $("#typeSelect").html(categories.join(''));
                if (companyTypeId != 0){
                    $.ajax(
                        {
                            url: "/api/admin/type/selectByIndustry/"+industryId,
                            type: "GET",
                            dataType: "json",
                            async: false,
                            success: function (data, textStatus, jqXHR) {
                                var categories = [];
                                data.data.map(function (type) {
                                    categories.push('<option value="');
                                    categories.push(type.id);
                                    categories.push('" ');
                                    categories.push('hassubinfo="true">');
                                    categories.push(type.name);
                                    categories.push('</option>');
                                });
                                $("#typeSelect").html(categories.join(''));
                                $("#typeSelect").val(companyTypeId);
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                toastr.error(errorThrown, textStatus);
                            }
                        });
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $.ajax(
        {
            url: Config.selectIndustryUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="" hassubinfo="true">请选择</option>');
                data.data.map(function (industry) {
                    categories.push('<option value="');
                    categories.push(industry.id);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(industry.name+"("+industry.companyCommission+"%)");
                    categories.push('</option>');
                });
                $("#industrySelect").html(categories.join(''));
                if (companyTypeId != 0){
                    console.log(industryId);
                    $("#industrySelect").val(industryId);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $.ajax(
        {
            url: '/api/admin/goods',
            type: "GET",
            data:{page:1,goodsProviderId:393,goodsOnline:1},
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var goodsList = [];
                goodsList.push('<option value="" hassubinfo="true">请选择商品</option>');
                data.data.map(function (goods) {
                    goodsList.push('<option value="');
                    goodsList.push(goods.goodsId);
                    goodsList.push('" ');
                    goodsList.push('hassubinfo="true">');
                    goodsList.push(goods.goodsName);
                    goodsList.push('</option>');
                });
                $("#goodsSelect").html(goodsList.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $('#goodsSelect').change(function () {
        if($("#goodsSelect").val() == ""){
            toastr.error("请选择商品");
        } else {
            $.ajax({
                url: '/api/admin/fjGoods',
                type: "POST",
                data: {goodsId:$("#goodsSelect").val(),companyId:$("#companyId").val()},
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    toastr.success("添加成功");
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        }
    });

    $("#industrySelect").change(function () {
        var industryId=$(this).val();
        $.ajax(
            {
                url: "/api/admin/type/selectByIndustry/"+industryId,
                type: "GET",
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    var categories = [];
                    categories.push('<option value="" hassubinfo="true">请选择</option>');
                    data.data.map(function (type) {
                        categories.push('<option value="');
                        categories.push(type.id);
                        categories.push('" ');
                        categories.push('hassubinfo="true">');
                        categories.push(type.name);
                        categories.push('</option>');
                    });
                    $("#typeSelect").html(categories.join(''));
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
    });
    $("#typeSelect").change(function () {
        $("input[id=companyTypeId]").val($(this).val());

    });

    $("#skCode").html("<img style='width: 300px;height: 300px' src="+$("input[id=sk]").val()+">");

    console.log($("input[id=sk]").val());
    // $($("#province option")[0]).html($("input[id=pr]").val());
    // $($("#city option")[0]).html($("input[id=ct]").val());
    // $($("#district option")[0]).html($("input[id=dr]").val());

    $.ajax(
        {
            url: "/api/configs/host/api",
            type: "GET",
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                var qrcode = new QRCode("qrcode", {
                    text: "" + data + "/wap/wx/login?fk=1-14-" + $("input[id=userId]").val() + "-" + $("input[id=companyId]").val() + "",
                    width: 300,
                    height: 300,
                    colorDark: "#0A0A0A",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H
                });
                $("#qr").val("");
                $("#qrcode img").attr("src", qrcode);
            }
        });
    $('input[id=id]').val($('input[id=companyId]').val());
    $('input:radio[name="redirectType"]').filter('[value="'+$("input[id=redirectType]").val()+'"]').attr('checked', true);
    $.ajax(
        {
            url: Config.selectLogisticsNameUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var logisticsName = [];
                logisticsName.push('<option value="">选择</option>');
                data.data.map(function (logistics) {
                    logisticsName.push('<option value="');
                    logisticsName.push(logistics.logisticsId);
                    logisticsName.push('" ');
                    logisticsName.push('hassubinfo="true">');
                    logisticsName.push(logistics.name);
                    logisticsName.push('</option>');
                });
                $(".logisticsId").append(logisticsName.join(''));
            }
        });
        $.ajax(
            {
                url: "/api/districts/page",
                type: "GET",
                data: {parentid: 0, page: 1, rows: 1000},
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    var districts = [];
                    districts.push('<option value="">选择</option>');
                    data.data.map(function (district) {
                        districts.push('<option value="');
                        districts.push(district.id);
                        districts.push('" ');
                        districts.push('hassubinfo="true">');
                        districts.push(district.name);
                        districts.push('</option>');
                    });
                    $(".provinceId").append(districts.join(''));
                }
            });
    $("[name=coType]").val($("#coType1").val());
    $("[name=coPayType]").val($("#coPayType1").val());
    $("input[class=companyId]").val($("input[id=companyId]").val());
    $("#discountType").val($("input[id=thisDiscountType]").val());
    $('#buttonGoback').click(function () {
        history.go(-1);
        location.reload();
        return false;
    });
    $("#company_list").jqGrid({
        datatype: "json",
        url: Config.selectUrl,
        height: 450,
        postData:{companyId:$("input[id=companyId]").val()},
        styleUI:  'Bootstrap',
        autowidth: true,
        shrinkToFit: true,
        rowNum: 12,
        colNames: ["编号", "省","快递公司", "运费","首重","续重价格", "时间"],
        colModel: [{
            name: "expriceId",
            index: "expriceId",
            editable: false,
            sorttype: "int",
            search: true
        }, {
            name: "provinceName",
            index: "provinceName",
            editable: true
        },{
            name: "logisticsName",
            index: "logisticsName",
            editable: true
        }, {
            name: "price",
            index: "price",
            editable: true
        }, {
            name: "heightBase",
            index: "heightBase",
            editable: true
        }, {
            name: "heightExtraPrice",
            index: "heightExtraPrice",
            editable: true
        },{
            name: "ctime",
            index: "ctime",
            editable: true
        }],
        cellEdit: true,
        cellsubmit: 'remote',
        cellurl: Config.updateUrlForCellEdit,
        pager: "#pager_company_list",
        jsonReader: {
            root: "data", "page": "page", total: "total",
            records: "records", repeatitems: false, id: "expriceId"
        },
        viewrecords: true,
        hidegrid: false,
        gridComplete: function () {
            dataWrapper();
            // var width = $(".rt-temp-width").width();
            // $("#company_list").setGridWidth(width);
        }
    });
    jQuery("#company_list").jqGrid('navGrid', '#pager_company_list', {add: false, edit: false, del: false});
    $(window).bind("resize", function () {
        var width = $(".jqGrid_wrapper").width();
        $("#company_list").setGridWidth(width);
    });

});
$('#submitaudit').click(function () {
    $("#ajaxfromdata").validate();
    if ($('#ajaxfromdata').valid()) {
        var postData = $('#ajaxfromdata').serializeArray();
        $.ajax({
            url: Config.updateAuditUrl,
            type: "GET",
            data: postData,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                toastr.success(data.msg, data.title);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    }

    return false;
});
$('#submitUpdate').click(function () {
    $("#ajaxform").validate();
    if ($('#ajaxform').valid()) {
        //var businessInspectTime =  dateToEpoch($("#businessInspect").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
        var businessEffectiveTime =  dateToEpoch($("#businessEffective").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
        var businessStartTime =  dateToEpoch($("#beginDateOne").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
        var businessEndTime =  dateToEpoch($("#endDateOne").val()) * 1 + 16 * 60 * 60 * 1000 - 1;
        if (!$("input[name=districtId]").val()){
            toastr.error("请选择地区");
            return false;
        }
        // if (isNaN(businessInspectTime)){
        //     toastr.error("请选择营业许可检查时间");
        //     return false;
        // }
        if (isNaN(businessEffectiveTime)){
            toastr.error("请选择营业许有效时间");
            return false;
        }
        if (isNaN(businessStartTime)){
            toastr.error("请选择营业开始时间");
            return false;
        }
        if (isNaN(businessEndTime)){
            toastr.error("请选择营业结束时间");
            return false;
        }
        //$("#businessInspect").val(businessInspectTime);
        $("#businessEffective").val(businessEffectiveTime);
        $("#beginDateOne").val(businessStartTime);
        $("#endDateOne").val(businessEndTime);
        $("#provinceIds").val($('#province option:selected').text());
        $("#cityIds").val($('#city option:selected').text());
        $("#districtIds").val($('#district option:selected').text());
        var postData = $('#ajaxform').serializeArray();
        $.ajax({
            url: Config.updateUrl,
            type: "PUT",
            data: postData,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                toastr.success(data.msg, data.title);
                load();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    }

    return false;
});

$('#submitExUpdate').click(function () {
    var logisticsId = $('#logisticsId option:selected').val();
    var price = $('input[name=price]').val() * 100;
    var provinceId = $('#provinceId option:selected').val();

    $.ajax({
        url: Config.updateExUrl,
        type: "PUT",
        data: {logisticsId: logisticsId, price: price, provinceId: provinceId},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            $('input[name=price]').val("")
            toastr.success(data.msg, data.title);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error(errorThrown, textStatus);
        }
    });
    jQuery("#company_list").trigger("reloadGrid");
    return false;
});

$("#perform_search").click(function () {
    var postdata = $("#company_list").jqGrid('getGridParam', 'postData');
    postdata._search = true;
    if ($('#logisticsId option:selected').val() != "") {
        postdata.logisticsId = $('#logisticsId option:selected').val();
    }
    if ($('#provinceId option:selected').val() != "") {
        postdata.provinceId = $('#provinceId option:selected').val();
    }
    jQuery("#company_list").trigger("reloadGrid", [{page: 1}]);
});
function dataWrapper() {
    var ids = jQuery("#company_list").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var dataFromTheRow = jQuery('#company_list').jqGrid('getRowData', id);
        dataFromTheRow.ctime = new Date(dataFromTheRow.ctime * 1).yyyymmddhhmmss();
        jQuery("#company_list").jqGrid('setRowData', ids[i], {
            price: toFixedForPrice(dataFromTheRow.price),
            heightExtraPrice:toFixedForPrice(dataFromTheRow.heightExtraPrice),
            ctime: dataFromTheRow.ctime
        });
    }
}

function load() {
    var businessStartTime = new Date($("#businessStartTime").val() * 1).yyyymmddhhmmss();
    var newBusinessStartTime = businessStartTime.substring(0,10);
    var businessEndTime = new Date($("#businessEndTime").val() * 1).yyyymmddhhmmss();
    var newBusinessEndTime = businessEndTime.substring(0,10);
    //var businessInspectTime = new Date($("#businessInspectTime").val() * 1).yyyymmddhhmmss();
    //var newBusinessInspectTime = businessInspectTime.substring(0,10);
    var businessEffectiveTime = new Date($("#businessEffectiveTime").val() * 1).yyyymmddhhmmss();
    var newBusinessEffectiveTime = businessEffectiveTime.substring(0,10);
    $("#beginDateOne").val(newBusinessStartTime);
    $("#endDateOne").val(newBusinessEndTime);
    //$("#businessInspect").val(newBusinessInspectTime);
    $("#businessEffective").val(newBusinessEffectiveTime);
    var companyStatus = $("#companyStatus").val();
    if(companyStatus == 1){
        $("#companyStatus1").attr("checked","checked");
    } else if(companyStatus == 2){
        $("#companyStatus2").attr("checked","checked");
    } else {
        $("#companyStatus0").attr("checked","checked");
    }
}